﻿using Microsoft.Data.SqlClient;
using SqlserverPool.Client;

namespace SqlserverPool.Console
{
    public class ToDoRepo : Repository<TodoEntity>
    {
        private string _connectionString;
        public ToDoRepo(string connectionString) : base(connectionString)
        {
            _connectionString = connectionString;
        }

        public async Task<List<TodoEntity>> GetAllAsync(string query, SqlParameter[] parameters)
        {
            try
            {
                List<TodoEntity> entities = new List<TodoEntity>();

                using (SqlConnection connection = new SqlConnection(_connectionString))
                {
                    using (SqlCommand command = new SqlCommand(query, connection))
                    {
                        command.Parameters.AddRange(parameters);
                        await connection.OpenAsync();
                        using (SqlDataReader reader = await command.ExecuteReaderAsync())
                        {
                            while (await reader.ReadAsync())
                            {
                                // Mapping logic to convert data reader to entity of type T
                                TodoEntity entity = MapEntity(reader);
                                entities.Add(entity);
                            }
                        }
                    }
                }

                return entities;
            }
            catch (Exception ex)
            {
                throw;
            }

        }

        private TodoEntity MapEntity(SqlDataReader reader)
        {
            var todoEntity = new TodoEntity
            {
                ToDoID = reader.GetString(reader.GetOrdinal("ToDoID")),
                CCFNumber = reader.GetString(reader.GetOrdinal("CCFNumber")),
                Title = reader.GetString(reader.GetOrdinal("Title")),
                Detail = reader.GetString(reader.GetOrdinal("Detail")),
                Status = reader.GetInt32(reader.GetOrdinal("Status")),
                CreateDate = reader.GetDateTime(reader.GetOrdinal("CreateDate"))
            };
            return todoEntity;
        }
    }
}
